package com.hzgj.bcl.soa.command;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.hzgj.bcl.soa.collector.JmxCollector;
import com.hzgj.bcl.soa.config.ServerDef;
import com.hzgj.bcl.soa.config.ServiceDef;
import com.hzgj.bcl.soa.registry.RegistryUpdater;
import com.hzgj.bcl.soa.util.Constants;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import static com.hzgj.bcl.soa.command.CommandsInitializer.REG_COMMAND;

/**
 * Created by Administrator on 2016/9/18.
 */
public class UpdateServiceCommand extends JmxInvokeCommand {

    @Override
    public String getName() {
        return "updateServices";
    }

    @Override
    Map<String, Object> jmxInvoke(JmxCollector jmxCollector, CommandOptions commandOptions, String host, String port) {
        Map<String, Object> result = Maps.newHashMap();
        try {
            String services = commandOptions.params.get("services")[0];
            String[] version_param = commandOptions.params.get("version");
            String[] group_param = commandOptions.params.get("group");
            String version = null;
            if (version_param != null) {
                version = version_param[0];
            }
            String group = null;
            if (group_param != null) {
                group = group_param[0];
            }
            String[] _ss = services.split(",");
            List<ServiceDef.Attr> attrs = Lists.newArrayList();
            for (String sName : _ss) {
                ServiceDef.Attr attr = new ServiceDef.Attr();
                attr.setInterface(sName);
                attr.setVersion(version);
                attr.setGroup(group);
                ServerDef serverDef = new ServerDef();
                serverDef.setPort(Integer.parseInt(port));
                serverDef.setHost(host);
                attr.setServerDef(serverDef);
                attrs.add(attr);
            }
            RegistryUpdater.Result ret = (RegistryUpdater.Result) jmxCollector.invoke(Constants.getRegistryServiceObjectName(), "updateServices",
                    new Object[]{attrs}, new String[]{List.class.getName()});
            if (!ret.isSuccess()) {
                result.put("message", ret.getInfo());
                result.put("status", "failure");
            } else {
                result.put("status", "success");
                result.put("message", "update success.");
                RegistryCommand registryCommand = CommandsInitializer.getCommand(REG_COMMAND);
                registryCommand.updateServiceInfo(host + ":" + port, Arrays.asList(_ss));
            }
        } catch (Exception e) {
            logger.error("{}", e);
            result.put("message", e.getMessage());
            result.put("status", "failure");
        }
        return result;
    }
}
